package com.weibo.survey.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.weibo.survey.dao.BaseDao;

public abstract class BaseDaoImpl<T> implements BaseDao<T> {

	protected Class<T> clazz;

	@Resource(name = "sessionFactory")
	protected SessionFactory sf;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class<T>) type.getActualTypeArguments()[0];
	}

	@Override
	public void saveEntity(T t) {
		sf.getCurrentSession().save(t);
	}

	@Override
	public void updateEntity(T t) {
		sf.getCurrentSession().update(t);
	}

	@Override
	public void saveOrUpdateEnity(T t) {
		sf.getCurrentSession().saveOrUpdate(t);
	}

	@Override
	public void deleteEntity(T t) {
		sf.getCurrentSession().delete(t);
	}

	@Override
	public void batchByHql(String hql, Object... objs) {
		Query query = sf.getCurrentSession().createQuery(hql);
		if (objs != null && objs.length > 0) {
			for (int i = 0; i < objs.length; i++) {
				query.setParameter(i, objs[i]);
			}
		}
		query.executeUpdate();
	}

	@Override
	@SuppressWarnings("unchecked")
	public T getEntity(int id) {
		return (T) sf.getCurrentSession().get(clazz, id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public T loadEntity(int id) {
		return (T) sf.getCurrentSession().load(clazz, id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public T getEntityByHql(String hql, Object... objs) {
		Query query=sf.getCurrentSession().createQuery(hql);
		if (objs != null && objs.length > 0) {
			for (int i = 0; i < objs.length; i++) {
				query.setParameter(i, objs[i]);
			}
		}
		return (T) query.uniqueResult();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> getEntitiesByHql(String hql, Object... objs) {
		Query query=sf.getCurrentSession().createQuery(hql);
		if (objs != null && objs.length > 0) {
			for (int i = 0; i < objs.length; i++) {
				query.setParameter(i, objs[i]);
			}
		}
		return query.list();
	}

}
